package com.random.fox.whatspay;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.random.fox.whatspay.bean.Account;
import com.random.fox.whatspay.bean.Categories;
import com.random.fox.whatspay.bean.Cost;
import com.random.fox.whatspay.bean.Unit;
import com.random.fox.whatspay.greendao.DaoMaster;
import com.random.fox.whatspay.greendao.DaoSession;
import com.random.fox.whatspay.greendao.dao.AccountDao;
import com.random.fox.whatspay.greendao.dao.CategoriesDao;
import com.random.fox.whatspay.greendao.dao.CostDao;

/**
 * Created by 渠 on 2014/8/29.
 */
public class AppContext extends Application {
    private DaoMaster master;
    private DaoSession daoSession;
    private AccountDao accountDao;
    private CostDao costDao;

    /**
     * 当前账户
     */
    private Account currentAccount;

    private String TAG = "AppContext";

    @Override
    public void onCreate() {
        super.onCreate();
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "accounts-db", null);
        SQLiteDatabase db = helper.getWritableDatabase();
        master = new DaoMaster(db);
        daoSession = master.newSession();
        accountDao = daoSession.getAccountDao();
        costDao = daoSession.getCostDao();

        SharedPreferences sp = getSharedPreferences(AppConfig.SP_NAME, Context.MODE_PRIVATE);
        long accountId = sp.getLong("accountId", 0);

        currentAccount = accountDao.loadByRowId(accountId);
        if (currentAccount == null){
            currentAccount = new Account(Unit.CHINA);
            currentAccount.setName("默认账户");
            accountDao.insert(currentAccount);
            Log.d(TAG,currentAccount.getId()+"");
            accountId = currentAccount.getId();
            sp.edit().putLong("accountId",accountId).commit();
        }

        CategoriesDao categoriesDao = daoSession.getCategoriesDao();
        Categories categories = new Categories();
        categories.setName("酱油");
        categoriesDao.insert(categories);
    }

    public AccountDao getAccountDao(){
        return accountDao;
    }

    public CostDao getCostDao(){
        return costDao;
    }

    public Account getCurrentAccount(){
        return currentAccount;
    }
}
